﻿using System;
using System.Collections.Generic;
using System.Text;
using Imple.Entities;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Imple.Ex;
using Imple.Util;

namespace Imple.Parse
{
    public class ParserProxy
    {
        private static ParserProxy _ins;
        private Dictionary<string, AbstractParser> _parserDic;
        private ParserProxy()
        {
            InitParserDictionary();
        }

        public static ParserProxy GetInstance()
        {
            if (null == _ins)
                _ins = new ParserProxy();
            return _ins;
        }

        private void InitParserDictionary()
        {
            _parserDic = new Dictionary<string, AbstractParser>();
            _parserDic.Add("2.0", new RSS2Parser());
            _parserDic.Add("0.92", new RSS92Parser());
            _parserDic.Add("0.91", new RSS91Parser());
        }

        /// <summary>
        /// read specified version first
        /// then dispatch parse issues 
        /// to concrete parser.
        /// </summary>
        /// <param name="stream">input stream</param>
        /// <returns>get real feed parser</returns>
        public AbstractParser GetParser(Stream stream)
        {
            if (null == stream)
                throw new ArgumentNullException("stream");

            string version = ReadVersion(stream);
            if (string.IsNullOrEmpty(version))
                throw new FormatInvalidException();
            if (!_parserDic.ContainsKey(version))
                throw new VersionNotSupportedException(version);

            return this._parserDic[version];
        }

        private string ReadVersion(Stream stream)
        {
            byte[] bs = new byte[stream.Length];
            stream.Read(bs, 0, bs.Length);

            return RSSVersionReader.ReadVersion(Encoding.UTF8.GetString(bs));
        }
    }
}